#include "client.h"
#include <QTextStream>
#include <QDebug>
#include <QHostAddress>
#include <QRandomGenerator>
Client::Client(QObject *parent)
    : QObject{parent},socket(new QTcpSocket(this))
{
    connect(socket,&QTcpSocket::readyRead,this,&Client::handleReadyRead);

}

void Client::connectToHost(const QString &hostname, quint16 port,const QString &username)
{
    socket->connectToHost(hostname,port);

    if(socket->waitForConnected(3000))
    {
        qDebug() << "连接成功";

    }
    else
    {
        qDebug() << "连接失败";
        return;
    }
    //发送用户名
    QByteArray data = username.toUtf8();
    socket->write(data);
    socket->waitForBytesWritten(3000);

}



void Client::handleReadyRead()
{
    //读取数据
    QByteArray data = socket->readAll();
    //检查是否为文件传输
    if (data.startsWith("FILE:"))
    {
        //解析文件名和文件大小
        int colonpos = data.indexOf(':');
        QString fileName = data.mid(5,colonpos - 5);
        qint64 fileSize = data.mid(colonpos + 1).toLong();
        //创建文件
        file = new QFile(fileName);
        if (!file->open(QIODevice::WriteOnly))
        {
            qDebug() << "无法创建文件" << fileName;
            return;
        }

        //接收文件数据
        while(fileSize > 0)
        {
            QByteArray block = socket->read(qMin(fileSize,qint64(1024)));
            file->write(block);
            fileSize -= block.size();
        }

        file->close();

        qDebug() << "文件接收完成" << fileName;
    }
    else
    {
        emit messageReceived(QString::fromUtf8(data));
    }


}
